<template>
  <div style="background: white;height: 500px;">
    <div>
      <a-form :form="form">
        <a-row>
          <a-col :span="10">
            <div style="font-size: 16px;margin-top: 20px;margin-bottom:20px;margin-left:20px;color:#1890FF">
            </div>
          </a-col>
          <a-col :span="5">
            <a @click="tipInfo"><span style="color: red">i</span>导入说明</a>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="11" :sm="32">
            <a-form-item label="车场选择:" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
              <a-col :span="16">
                <a-select style="width: 100%;" v-decorator="['selectedParkCodeId',{}]" :options="parkCodeList">
                </a-select>
              </a-col>

            </a-form-item>
            <a-form-item label="有效期" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-radio-group v-model="isForever" @change="isForeverChange">
                <a-radio :value="1">永久期限</a-radio>
                <a-radio :value="0">自定义时间</a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item
                label="黑名单文件:"
                :label-col="{ span: 4,style:'height: 35px' }"
                :wrapper-col="{ span: 20,style:'height: 35px' }">
              <a-col
                  style="height: 100%"
                  :span="30">
                <a-row>
                  <a-col :span="8">
                    <p style="background-color: #EEEEEE;padding-left: 10px;line-height:32px;margin-top:4px;margin-bottom:0px;font-size:14px">
                      {{ fileName }}</p>
                  </a-col>
                  <a-col :span="4">
                    <a-upload accept=".xlsx,.xls" :file-list="fileList" style="width: 100%"
                              :before-upload="beforeUpload" :showUploadList="false">
                      <a-button size="default" style="width: 100%" class="colsty1" @click="fileChange">
                        <a-icon type="folder-open"/>
                        选择
                      </a-button>
                    </a-upload>
                  </a-col>
                  <a-col :span="4">
                    <span>下载模板：</span>
                  </a-col>
                  <a-col :span="4">
                    <a-button :ghost="true" class="colsty2" size="default" @click="handleExportXls('黑名单导入模板')">
                      <a-icon type="folder-open"/>
                      <span>点击下载模板</span>
                    </a-button>
                  </a-col>
                </a-row>
              </a-col>

            </a-form-item>

            <a-form-item label="导入方式" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-radio-group v-model="importType" @change="importTypeChange">
                <a-radio :value="1">忽略重复(以已存在记录为准)</a-radio>
                <a-radio :value="0">覆盖导入(以最新记录为准)</a-radio>
              </a-radio-group>
            </a-form-item>

          </a-col>
        </a-row>
        <a-form-item :label-col="{ span: 7 }" :wrapper-col="{ span: 19 }">
          <a-button
              class="colsty1"
              size="default"
              :disabled="fileList.length === 0"
              :loading="uploading"
              style="margin-left:9%"
              @click="handleCheck">
            <a-icon type="search"/>
            <span>文件检查</span>
          </a-button>

          <a-button
              class="colsty1"
              size="default"
              :disabled="!excelCheckResult"
              :loading="uploading"
              style="margin-left:9%"
              @click="handleUpload">
            <a-icon type="upload"/>
            <span>开始导入</span>
          </a-button>
          <span style="font-size: 15px;margin-top:0px;margin-bottom: 0px ;color: red">  说明：导入文件表格中的数据最大为500条</span>
        </a-form-item>
      </a-form>
    </div>

    <div>
      <a-card :bordered="false">
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <div v-show="progressShow">
            执行进度：
            <a-progress :stroke-color="{'0%': '#108ee9','100%': '#87d068',}" :percent="percent" style="width: 400px"/>
          </div>
          执行结果：
          共计<a style="font-weight: 600">{{ totalCount }}</a>条，
          正常<a style="font-weight: 600">{{ totalCount - failCount }}</a>条，
          失败<a style="font-weight: 600">{{ failCount }}</a>条
        </div>

        <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataResult"
            style="word-break: break-all"
        >
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script>
import {downFile, getAction, postAction} from "@api/manage";
import {JeecgListMixin} from "@/mixins/JeecgListMixin";

export default {
  name: "ParkBlackImport",
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      isForever: 1,
      importType: 1,
      totalCount: 0,
      failCount: 0,
      progressShow: false,
      percent: 0,
      weekday: "",
      fileList: [],
      dataResult: [],
      uploading: false,
      initCheckProgress: null,
      form: this.$form.createForm(this),
      parkCodeList: [],
      selectedParkCodeId: "",
      excelCheckResult: false,
      currDateTime: '',
      fileName: "请选择文件",
      headers: {
        authorization: 'authorization-text',
      },
      // 表头
      columns: [
        {
          title: '文件行号',
          align: 'center',
          dataIndex: 'id',
          width: 20,
        },
        {
          title: '车主/姓名',
          align: 'center',
          dataIndex: 'userName',
          width: 20,
        },
        {
          title: '车牌号',
          align: 'center',
          dataIndex: 'plateNo',
          width: 30,
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 20,
        },
        {
          title: '说明',
          align: 'center',
          dataIndex: 'message',
          width: 30,
        },
      ],
      downloadParam: {
        "isForever": "",
      },
      url: {
        list: "/blacklist/parkBlackList/findConfigParkInfo",
        importTemplate: "/blacklist/parkBlackList/importTemplate",
        importExcelCheck: "/blacklist/parkBlackList/importFromExcelCheck",
        getCheckProgress: "/blacklist/parkBlackList/getCheckProgress",
        importExcelUrl: "/blacklist/parkBlackList/importFromExcel",
      },
    };
  },
  mounted() {
    this.initConfigParkInfo();
  },
  destroyed() {
    this.clear()
  },
  methods: {
    tipInfo() {
      const h = this.$createElement;
      this.$info({
        title: '导入说明',
        content: h('div', {}, [
          h('p', '1.下载模板文件，并按格式要求填写车辆相关基本信息。'),
          h('p', '2.选择填写好的导入文件。'),
          h('p', '3.执行导入前您可以选择导入方式，即忽略重复或覆盖导入。'),
          h('p', '4.当有效期选择的为自定义时间方式，导入前支持选择指定周日。即指定周日下有效。'),
          h('p', '5.点击文件检查按钮，系统会检测文件正确性校验。当文件检查不通过时，请按照页面给出的错误提示，更正对应记录。当文件检查通过时，执行结果可在结果栏查看。'),
        ]),
        onOk() {
        },
      });
    },
    beforeUpload(file) {
      this.fileName = file.name;
      this.fileList = [...this.fileList, file];
      return false;
    },
    isForeverChange(e) {
      this.isForever = e.target.value
      this.excelCheckResult = false;
    },
    importTypeChange(e) {
      this.importType = e.target.value
    },
    fileChange(e) {
      this.excelCheckResult = false;
    },
    initConfigParkInfo() {
      const that = this
      getAction(this.url.list, {}).then(res => {
        if (res.success) {
          that.parkCodeList = []
          that.parkCodeList.push({
            value: res.result.parkCode,
            label: res.result.parkName
          })
          that.selectedParkCodeId = that.parkCodeList[0].value
          that.form.setFieldsValue({selectedParkCodeId: this.selectedParkCodeId})
        } else {
          this.$message.error(res.message);
        }
      })
    },
    //导入文件校验
    handleCheck() {
      this.totalCount = 0;
      this.failCount = 0;
      this.percent = 0;
      const {fileList} = this;
      this.dataResult = [];
      const formData = new FormData();
      let result = true;
      this.currDateTime = new Date().getTime();
      this.form.validateFields((err, values) => {
        if (this.isForever == 0) {
          if (!values.weekDay || !values.weekDay.length) {
            result = false;
          }
        }
      });



      formData.set("currDateTime", this.currDateTime);
      formData.set("isForever", this.isForever);
      fileList.forEach(file => {
        formData.set("files[]", file);
      });

      this.$nextTick(() => {
        this.uploading = true;
        this.progressShow = true;
        this.initCheckProgress = setInterval(this.handleCheckProgress, 1000);

        postAction(this.url.importExcelCheck, formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.excelCheckResult = true;
            this.totalCount = res.result[0].totalCount;
            this.failCount = 0;
          } else {
            this.excelCheckResult = false;
            if (res.result != null) {
              this.dataResult = res.result;
              this.totalCount = res.result[0].totalCount;
              this.failCount = res.result.length;
            }
          }
          this.clear();
          // this.progressShow = false;
          this.uploading = false;
        },(error) => {
          this.clear();
          this.uploading = false;
          this.$message.error("业务处理失败！");
        })
      })
    },

    handleCheckProgress() {
      const formData = new FormData();
      formData.set("currDateTime", this.currDateTime);
      postAction(this.url.getCheckProgress, formData).then((res) => {
        this.percent = res.result;
      })
    },

    clear() {
      clearInterval(this.initCheckProgress);
      this.initCheckProgress = null;
      this.percent = 100;
    },

    //导入
    handleUpload() {
      this.totalCount = 0;
      this.failCount = 0;
      this.percent = 0;
      const {fileList} = this;
      const formData = new FormData();
      let result = true;
      this.currDateTime = new Date().getTime();
      this.form.validateFields((err, values) => {
        if (this.isForever == 0) {
          if (!values.weekDay || !values.weekDay.length) {
            result = false;
          }
          this.weekDay = values.weekDay.join('、');
        }
      });


      formData.set("currDateTime", this.currDateTime);
      formData.set("isForever", this.isForever);
      formData.set("importType", this.importType);
      formData.set("weekDay", this.weekDay);
      fileList.forEach(file => {
        formData.set("files[]", file);
      });

      this.$nextTick(() => {

        this.uploading = true;
        this.progressShow = true;
        this.initCheckProgress = setInterval(this.handleCheckProgress, 1000);

        postAction(this.url.importExcelUrl, formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.dataResult = [];
            this.totalCount = res.result[0].totalCount;
            this.failCount = 0;
          } else {
            if (res.result != null) {
              this.dataResult = res.result;
              this.totalCount = res.result[0].totalCount;
              this.failCount = res.result.length;
            }
          }
          this.clear();
          // this.progressShow = false;
          this.uploading = false;
        },(error) => {
          this.clear();
          this.uploading = false;
          this.$message.error("业务处理失败！");
        })
      })
    },
    //下载导入模板
    handleExportXls(fileName) {
      let param = {...this.downloadParam};
      param.isForever = this.isForever;
      if (this.isForever == 1) {
        fileName = "黑名单导入模板(永久期限)";
      } else {
        fileName = "黑名单导入模板(自定义时间)";
      }
      downFile(this.url.importTemplate, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      })
    },
  },
}
</script>

<style scoped>

.colsty1 {
  background: #1890FF;
  color: white;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  border-width: 0px;

}

.colsty2 {
  color: #1890FF;
}

/deep/ .ant-upload.ant-upload-select.ant-upload-select-text {
  width: 100%;
}
</style>
